//
//  BankListViewController.swift
//  ShareCar
//
//  Created by 李帅 on 2019/1/7.
//  Copyright © 2019 changqingkeji. All rights reserved.
//

import UIKit
import Kingfisher

class BankListViewController: UITableViewController {
    var open = true
    var block: ((Bank.Item) ->())!
    private var data = [String: [Bank.Item]]() {
        didSet {
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        func choose(kqpayFlag: Int? = nil, returnFlag: Int? = nil) {
            Bank.list(flag: .all, kqpayFlag: kqpayFlag, returnFlag: returnFlag, success: { [weak self] items in
                if let items = items {
                    self?.setup(items: items)
                }
                
            }) { [weak self] msg in
                self?.showError(msg)
            }
        }
        
        if !open {
            title = "支持的银行列表"
            choose(kqpayFlag: 2)
            
        } else {
            choose(returnFlag: 2)
        }
    }
    private func setup(items: [Bank.Item]) {
        var data = [String: [Bank.Item]]()
        
        for i in items {
            var first = i.bankInitial
            first = first.uppercased()
            
            if data[first] == nil {
                data[first] = [Bank.Item]()
            }
            data[first]?.append(i)
        }
        
        for (k, v) in data {
            data[k] = v.sorted{ $0.bankName < $1.bankName }
        }
        
        self.data = data
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return data.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let keys = Array(data.keys).sorted()
        let key = keys[section]
        return data[key]?.count ?? 0
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        if let cell = cell as? BankCell {
            let keys = Array(data.keys).sorted()
            let key = keys[indexPath.section]
            if let item = data[key]?[indexPath.row] {
                cell.nameLabel.text = item.bankName
                
                let url = URL(string: kImageServerName + "/" + item.imagePath)
                cell.iconImage.kf.setImage(with: url, placeholder: UIImage(named: "bankCardDefaultImage"))
            }
        }
        
        return cell
    }
    
    override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return Array(data.keys).sorted()
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view1 = UIView()
        view1.backgroundColor = UIColor(hexString: "#ececf2")
        let keys = Array(data.keys).sorted()
        let label = UILabel(frame: CGRect(x: 15, y: 0, width: 200, height: 20))
        label.font = UIFont.systemFont(ofSize: 12.0)
        label.textColor = UIColor(hexString: "#0a0b41")
        label.text = keys[section]
        view1.addSubview(label)
        return view1
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if open {
            let keys = Array(data.keys).sorted()
            let key = keys[indexPath.section]
            if let item = data[key]?[indexPath.row] {
                block(item)
                navigationController?.popViewController(animated: true)
            }
        }

    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
